package com.bphx.android.activities;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.bphx.android.db.IOptionsHolder;
import com.bphx.android.db.Storage;
import com.bphx.android.exception.OptionsException;

import java.util.*;

import static android.R.layout.simple_dropdown_item_1line;
import static android.widget.Toast.*;
import static com.bphx.android.R.id.*;
import static com.bphx.android.R.layout.options;
import static com.bphx.android.R.string.errorInvalidWordsCount;
import static com.bphx.android.R.string.textOptionsSaved;
import static com.bphx.android.utils.Constants.*;
import static com.bphx.android.utils.Utils.isMoreThen;
import static org.apache.commons.lang.StringUtils.isEmpty;

/**
 * @author Vyacheslav Kovalyov
 * @version 1.0
 */
public class OptionsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(options);

        initViews();
        if (savedInstanceState == null) {
            loadOptions();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        optionsMap.put(SPEAKER_LOCALE, localesSpinner.getSelectedItem().toString());
        outState.putSerializable(OPTIONS, optionsMap);
        outState.putStringArrayList(SPINNER_ITEMS, spinnerItems);
        super.onSaveInstanceState(outState);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        optionsMap = (HashMap<String, String>) savedInstanceState.getSerializable(OPTIONS);
        spinnerItems = savedInstanceState.getStringArrayList(SPINNER_ITEMS);
        super.onRestoreInstanceState(savedInstanceState);

        populateOptions();
    }

    private void loadOptions() {
        IOptionsHolder holder = new Storage(this);

        optionsMap = new HashMap<String, String>();
        optionsMap.put(OPTION_WORDS_COUNT, holder.getOption(OPTION_WORDS_COUNT));
        optionsMap.put(SPEAKER_LOCALE, holder.getOption(SPEAKER_LOCALE));

        populateOptions();
    }

    private void populateOptions() {
        wordsCountTW.setText(optionsMap.get(OPTION_WORDS_COUNT));
        initSpinner();
        localesSpinner.setSelection(spinnerItems.indexOf(optionsMap.get(SPEAKER_LOCALE)));
    }

    private void initSpinner() {

        localesSpinner = (Spinner) findViewById(locales_spinner);

        if (spinnerItems == null) {
            Locale[] availableLocales = new Locale("en").getAvailableLocales();
            Set<String> set = new HashSet<String>();

            for (Locale locale : availableLocales) {
                set.add(locale.getLanguage());
            }

            spinnerItems = new ArrayList<String>(set);
        }

        localesSpinner.setAdapter(new ArrayAdapter<String>(this,
                simple_dropdown_item_1line, spinnerItems.toArray(new String[spinnerItems.size()])));
    }

    private void initViews() {
        wordsCountTW = (TextView) findViewById(max_word_option);

        findViewById(back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        findViewById(okButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    checkFields();
                } catch (OptionsException e) {
                    makeText(OptionsActivity.this, e.getMessage(), LENGTH_LONG).show();
                    return;
                }

                saveOptions();
                makeText(OptionsActivity.this, textOptionsSaved, LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private void saveOptions() {
        IOptionsHolder holder = new Storage(this);
        for (String key : optionsMap.keySet()) {
            holder.saveOption(key, optionsMap.get(key));
        }
    }

    private void checkFields() throws OptionsException {

        String wordsCountString = wordsCountTW.getText().toString().trim();

        if (isEmpty(wordsCountString) || isMoreThen(0, wordsCountString)) {
            optionsMap.put(OPTION_WORDS_COUNT, wordsCountString);
        } else {
            throw new OptionsException(this, getString(errorInvalidWordsCount));
        }

        optionsMap.put(SPEAKER_LOCALE, localesSpinner.getSelectedItem().toString());
    }

    private ArrayList<String> spinnerItems;
    private TextView wordsCountTW;
    private Spinner localesSpinner;
    private HashMap<String, String> optionsMap;
}